from __future__ import absolute_import
import xadmin
from .models import UserSettings, Log
from django.template.defaultfilters import slugify
import re
from django.utils.translation import ugettext_lazy as _, ugettext
from blog.models import *
from blog.utils import MyHashEncryptor as MyHash,get_timestamp_rand
from django.conf import settings

# class UserSettingsAdmin(object):
#     model_icon = 'fa fa-cog'
#     hidden_menu = True
#
# xadmin.site.register(UserSettings, UserSettingsAdmin)

@xadmin.sites.register(Log)
class LogAdmin(object):
    def link(self, instance):
        if instance.content_type and instance.object_id and instance.action_flag != 'delete':
            admin_url = self.get_admin_url(
                '%s_%s_change' % (instance.content_type.app_label, instance.content_type.model),
                instance.object_id)
            return "<a href='%s'>%s</a>" % (admin_url, _('Admin Object'))
        else:
            return ''

    link.short_description = ""
    link.allow_tags = True
    link.is_column = False

    list_display = ('action_time', 'user', 'ip_addr', '__str__', 'link')
    list_filter = ['user', 'action_time']
    search_fields = ['ip_addr', 'message']
    model_icon = 'fa fa-cog'


@xadmin.sites.register(Article)
class ArticleAdmin(object):
    """
        文章管理
    """
    # style_fields = {"body": "ckeditor"}
    model_icon = 'fa fa-font'
    search_fields = ['title', 'summary']
    list_display = ('title', 'create_date', 'update_date','author')
    list_filter = ('author','is_public')
    # list_filter = ('category',)
    exclude = ('author', 'views','slug','keywords')

    def has_delete_permission(self, *args, **kwargs):
        # if args:
        #     return True
        return True
    # 自动添加管理员,重写虚拟环境根目录下\Lib\site-packages\xadmin\views\edit.py中的save_models方法

    def save_models(self):
        flag = self.org_obj is None and 'create' or 'change'
        if flag == 'create':
            num_sixteen =  get_timestamp_rand() + "Article"
            slug_hash = MyHash.myencryped('md5', num_sixteen)
            # author_id = Ouser.filter(username=self.request.user)
            # print('author_id:',author_id)
            self.new_obj.author = self.request.user
            # print(self.new_obj.author)
            self.new_obj.slug = slugify("-".join(re.findall(r'[0-9a-f]{8}', slug_hash)))
            old_body_150, old_summary = '', ''
        else:
            old_body_150 = Article.objects.filter(id=self.new_obj.id).values('body')[0].get('body')[:150]
            old_summary = Article.objects.filter(id=self.new_obj.id).values('summary')[0].get('summary')
        # print(self.new_obj.summary)
        # print(old_summary)
        if (flag == 'create' and self.new_obj.summary == getattr(settings,'DEFALUT_SUMMARY')) \
                or (flag == 'change' and old_body_150 == old_summary \
                and self.new_obj.body[:150] != old_summary \
                or self.new_obj.summary == ''):
            self.new_obj.summary = self.new_obj.body[:150]
        super().save_models()

    def queryset(self):
        """当前用户只能看到自己的数据"""
        user = self.request.user
        if user.is_superuser:
            # 管理员可以查看所有数据
            return self.model._default_manager.get_queryset()
        # 当前用户只能查看自己的数据
        return self.model.objects.filter(author=user)


@xadmin.sites.register(Keyword)
class KeywordAdmin(object):
    '''
        关键词管理
    '''
    model_icon = 'fa fa-question'


@xadmin.sites.register(Tag)
class TagAdmin(object):
    '''
        标签管理
    '''
    model_icon = 'fa fa-tag'
    exclude = ('slug',)

    def save_models(self):
        flag = self.org_obj is None and 'create' or 'change'
        if flag == 'create':
            num_sixteen = get_timestamp_rand() + "Tag"
            slug_hash = MyHash.myencryped('md5', num_sixteen)
            self.new_obj.slug = slugify("-".join(re.findall(r'[0-9a-f]{8}', slug_hash)))
        super().save_models()
    def has_delete_permission(self, *args, **kwargs):
        # if args:
        #     return True
        return True

@xadmin.sites.register(Category)
class CategoryAdmin(object):
    '''
    分类管理
    '''
    model_icon = 'fa fa-align-left'
    exclude = ('slug',)
    def save_models(self):
        flag = self.org_obj is None and 'create' or 'change'
        if flag == 'create':
            num_sixteen =  get_timestamp_rand() + "Category"
            slug_hash = MyHash.myencryped('md5', num_sixteen)
            self.new_obj.slug = slugify("-".join(re.findall(r'[0-9a-f]{8}', slug_hash)))
        super().save_models()
    def has_delete_permission(self, *args, **kwargs):
        # if args:
        #     return True
        return True


@xadmin.sites.register(Timeline)
class TimelineAdmin(object):
    '''
    时间线管理
    '''
    model_icon = 'fa fa-clock-o'


@xadmin.sites.register(Carousel)
class CarouselAdmin(object):
    '''
        幻灯片管理
    '''
    model_icon = 'fa fa-picture-o'


@xadmin.sites.register(Silian)
class SilianAdmin(object):
    '''
        死链管理
    '''
    model_icon = 'fa fa-times-circle'

@xadmin.sites.register(FriendLink)
class FriendLinkAdmin(object):
    '''
        友链管理
    '''
    model_icon = 'fa fa-check-circle'

@xadmin.sites.register(AboutBlog)
class AboutBlogAdmin(object):
    '''
        关于管理
    '''
    list_display = ('short_body', 'create_date', 'update_date')
    model_icon = 'fa fa-info-circle'

    def short_body(self, obj):
        return '自由编辑 About 页面的内容，支持 markdown 语法。'

    short_body.short_description = 'AboutBlog'

    # 限制用户权限，只能超管可以编辑
    def get_queryset(self, request):
        qs = super(AboutBlogAdmin, self).get_queryset(request)
        if request.user.is_superuser:
            return qs
        return None
    def has_delete_permission(self, *args, **kwargs):
        # if args:
        #     return True
        return True


#主题切换
from xadmin import views

@xadmin.sites.register(views.BaseAdminView)
class BaseSetting(object):
    enable_themes = True
    use_bootswatch = True


from comment.models import *
@xadmin.sites.register(ArticleComment)
class CommentAdmin(object):
    date_hierarchy = 'create_date'
    list_display = ('id', 'author', 'belong', 'create_date', 'show_content')
    list_filter = ('author', 'belong',)
    ordering = ('-id',)
    # 设置需要添加a标签的字段
    list_display_links = ('id', 'show_content')
    search_fields = ('author__username', 'belong__title')

    # 使用方法来自定义一个字段，并且给这个字段设置一个名称
    def show_content(self, obj):
        return obj.content[:30]

    show_content.short_description = '评论内容'

@xadmin.sites.register(Notification)
class NotificationAdmin(object):
    date_hierarchy = 'create_date'
    list_display = ('id', 'create_p', 'create_date', 'comment', 'is_read')
    list_filter = ('create_p', 'is_read',)
    search_fields = ('create_p__username', 'comment__content')






